package com.example.my_test_2.controller;

import com.example.my_test_2.dto.UserDto;
import com.example.my_test_2.pojo.Purchase;
import com.example.my_test_2.pojo.User;
import com.example.my_test_2.repos.UserRepository;
import com.example.my_test_2.service.AdminService;
import com.example.my_test_2.service.SalesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;

//管理控制
@RestController
@RequestMapping("/api/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private SalesService salesService;

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/users")
    //得到所有用户
    public List<User> getAllUsers() {
        try {
            return adminService.getAllUsers();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to fetch users", e);
        }
    }
    //得到所有购买信息
    @GetMapping("/purchases")
    public List<Purchase> getAllPurchases() {
        return adminService.getAllPurchases();
    }

//得到所有商店得销售信息
//    @GetMapping("/sales")
//    public List<>
    @GetMapping("/getAllSales")
    public List<Purchase> getAllPurchase(){
        return salesService.getPurchasesRecord();
    }


    @PostMapping("/adminlogin")
    public User adminLogin(@RequestBody UserDto userDto) {
        User user = userRepository.findByUserName(userDto.getUserName());
        if (user != null && user.getUserPwd().equals(userDto.getUserPwd()) && "管理员".equals(user.getRole().getRoleName())) {
            return user; // 用户存在，密码正确，且是管理员
        } else {
            return null; // 登录失败，返回null
        }
    }


}